package com.dev.ac.handler;

import com.dev.ac.annotation.Login;
import com.dev.ac.common.Const;
import com.dev.ac.exception.WebException;
import com.dev.ac.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 付
 * @Date 2024-04-14 16:47
 * @Version 1.0
 * @description
 * @since 1.0
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
	@Resource
	JwtUtil jwtUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println(request.getHeader("token"));
		Login annotation;
		System.out.println("进入了");
		// 判断当前请求是否为方法，如果是，就对其进行注解判断
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
		} else {
			System.out.println("这里过滤1");
			return true;
		}

		if (annotation == null) {
			System.out.println("这里过滤2");
			return true;
		}

		String token = request.getHeader("token");
		String issuer = annotation.issuer();
		System.out.println("--->" + token);
		// 判断token是否合法
		if (!StringUtils.hasText(token)) {
			throw new WebException("请先登录1");
		}
		if (!StringUtils.hasText(issuer)) {
			throw new WebException("请先登录2");
		}


		System.out.println("获取的token------" + token);
		// 判断token内容是否存在，且是否超时
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_USER);
		System.out.println(claim);
		if (claim == null) {
			claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);

		}
		System.out.println(claim + "==========");
		//System.out.println(claim.getExpiration() + "---------" + jwtUtil.isTokenExpired(claim.getExpiration()));
		 if (claim == null || jwtUtil.isTokenExpired(claim.getExpiration())) {
			throw new WebException("请先登录");
		}
		if (!annotation.issuer().equals(claim.getIssuer()) && (annotation.issuer().equals(Const.GRADE_ADMIN))) {
			throw new WebException("抱歉，权限不足");
		}
		System.out.println("这里输出以下拦截器的信息--" + annotation.issuer() + "-" + claim.getIssuer());

		// 将用户信息存储到session
		request.getSession().setAttribute("username", Integer.valueOf(claim.getSubject()));
		System.out.println(request.getAttribute("username"));
		return true;
	}
}

